package com.atguigu.gmall.payment.controller;


import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.atguigu.gmall.model.enums.PaymentStatus;
import com.atguigu.gmall.model.enums.PaymentType;
import com.atguigu.gmall.model.payment.PaymentInfo;
import com.atguigu.gmall.payment.config.AlipayConfig;
import com.atguigu.gmall.payment.service.AlipayService;
import com.atguigu.gmall.payment.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@Controller
@RequestMapping("/api/payment/alipay")
@Slf4j
public class AlipayController {

    @Autowired
    private AlipayService alipayService;
    @Autowired
    private PaymentService paymentService;

    //进入支付宝 支付页面
    @GetMapping("/submit/{orderId}")
    @ResponseBody
    public String submitPayment(@PathVariable(name = "orderId") Long orderId){
        String form = alipayService.createAlipay(orderId);
        return form;
    }
    //同步回调
    @GetMapping("/callback/return")
    public String callbackReturn(){

        return "redirect:" + AlipayConfig.return_order_url;
    }
    //异步回调
    @PostMapping("/callback/notify")
    @ResponseBody
    public String callbackNotify(@RequestParam Map<String, String> paramsMap){
        try {
            boolean signVerified = AlipaySignature.rsaCheckV1(paramsMap, AlipayConfig.alipay_public_key,
                    AlipayConfig.charset, AlipayConfig.sign_type);
            if(signVerified){
                //验证成功
                // TODO 验签成功后，按照支付结果异步通知中的描述，
                //  对支付结果中的业务内容进行二次校验，校验成功后在response中返回success
                //  并继续商户自身业务处理，校验失败返回failure
                //商户订单号
                String out_trade_no = paramsMap.get("out_trade_no");
                //交易状态
                String trade_status = paramsMap.get("trade_status");
                if("TRADE_SUCCESS".equalsIgnoreCase(trade_status) ||
                        "TRADE_FINISHED".equalsIgnoreCase(trade_status)){

                    //交易成功之后  判断支付信息 支付状态  如果是已支付或是已完成或是已关闭 就不要更新支付状态
                    PaymentInfo paymentInfo = paymentService.
                            getPaymentInfo(out_trade_no, PaymentType.ALIPAY.name());

                    if(PaymentStatus.PAID.name().equals(paymentInfo.getPaymentStatus())
                       || PaymentStatus.ClOSED.name().equals(paymentInfo.getPaymentStatus())){
                        return "failure";
                    }
                    //更新支付信息支付状态
                    paymentService.paySuccess(paymentInfo,paramsMap);
                    return "success";
                }else{
                    return "failure";
                }
            }else{
                //验证失败
                log.error("接收支付宝异步回调数据：验证失败" + JSON.toJSONString(paramsMap));
                return "failure";
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return "failure";
    }

    //退钱
    @GetMapping("/refund/{out_trade_no}")
    @ResponseBody
    public String refund(@PathVariable(name = "out_trade_no") String out_trade_no){
       return alipayService.refund(out_trade_no);
    }

}
